/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dialogs.perfil;

import dao.Dao;
import dao.DaoUsuario;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import libcontrol.model.Perfil;
import libcontrol.model.Atividade;
import libcontrol.model.Usuario;

/**
 *
 * @author filipe
 */
public class JDialogVerPerfil extends javax.swing.JDialog {

    private Perfil perfil;

    JDialogVerPerfil(JFrame parent, boolean modal, Perfil perfil) {
        super(parent, modal);
        initComponents();
        this.perfil = perfil;
        if (perfil.getNome().equals("Administrador")) {
            jButtonExcluirPerfil.setEnabled(false);
        }
        preencherCampos();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanelPerfil = new javax.swing.JPanel();
        jLabelNome = new javax.swing.JLabel();
        jTextFieldNome = new javax.swing.JTextField();
        jLabelTempoMaximo = new javax.swing.JLabel();
        jLabelNumeroMaximo = new javax.swing.JLabel();
        jTextFieldTempoMaximo = new javax.swing.JTextField();
        jTextFieldNumeroMaximo = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jListAtividadesAdicionadas = new javax.swing.JList();
        jLabelAtividades = new javax.swing.JLabel();
        jButtonFechar = new javax.swing.JButton();
        jButtonExcluirPerfil = new javax.swing.JButton();
        jButtonAlterarPerfil = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabelNome.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
        jLabelNome.setText("Nome do Perfil:");

        jTextFieldNome.setEnabled(false);

        jLabelTempoMaximo.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
        jLabelTempoMaximo.setText("Tempo Máximo de Empréstimo:");

        jLabelNumeroMaximo.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
        jLabelNumeroMaximo.setText("Número Máximo de Empréstimos:");

        jTextFieldTempoMaximo.setEnabled(false);

        jTextFieldNumeroMaximo.setEnabled(false);

        jListAtividadesAdicionadas.setEnabled(false);
        jScrollPane1.setViewportView(jListAtividadesAdicionadas);

        jLabelAtividades.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
        jLabelAtividades.setText("Atividades Permitidas para esse Perfil");

        jButtonFechar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/cancelar.png"))); // NOI18N
        jButtonFechar.setText("Fechar");
        jButtonFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonFecharActionPerformed(evt);
            }
        });

        jButtonExcluirPerfil.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/lixeira.png"))); // NOI18N
        jButtonExcluirPerfil.setText("Excluir Perfil");
        jButtonExcluirPerfil.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonExcluirPerfilActionPerformed(evt);
            }
        });

        jButtonAlterarPerfil.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/editar.png"))); // NOI18N
        jButtonAlterarPerfil.setText("Alterar Perfil");
        jButtonAlterarPerfil.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAlterarPerfilActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanelPerfilLayout = new javax.swing.GroupLayout(jPanelPerfil);
        jPanelPerfil.setLayout(jPanelPerfilLayout);
        jPanelPerfilLayout.setHorizontalGroup(
            jPanelPerfilLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelPerfilLayout.createSequentialGroup()
                .addGroup(jPanelPerfilLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelPerfilLayout.createSequentialGroup()
                        .addGroup(jPanelPerfilLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanelPerfilLayout.createSequentialGroup()
                                .addGap(24, 24, 24)
                                .addGroup(jPanelPerfilLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabelTempoMaximo)
                                    .addComponent(jLabelNome)
                                    .addComponent(jLabelNumeroMaximo)))
                            .addGroup(jPanelPerfilLayout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jButtonFechar, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanelPerfilLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextFieldNome, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanelPerfilLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jTextFieldNumeroMaximo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)
                                .addComponent(jTextFieldTempoMaximo, javax.swing.GroupLayout.Alignment.LEADING))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelPerfilLayout.createSequentialGroup()
                                .addGap(8, 8, 8)
                                .addComponent(jButtonExcluirPerfil)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonAlterarPerfil))))
                    .addGroup(jPanelPerfilLayout.createSequentialGroup()
                        .addGap(207, 207, 207)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(32, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelPerfilLayout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jLabelAtividades)
                .addGap(111, 111, 111))
        );
        jPanelPerfilLayout.setVerticalGroup(
            jPanelPerfilLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelPerfilLayout.createSequentialGroup()
                .addGap(36, 36, 36)
                .addGroup(jPanelPerfilLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelNome)
                    .addComponent(jTextFieldNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanelPerfilLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelTempoMaximo)
                    .addComponent(jTextFieldTempoMaximo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanelPerfilLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelNumeroMaximo)
                    .addComponent(jTextFieldNumeroMaximo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29)
                .addComponent(jLabelAtividades)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 239, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(36, 36, 36)
                .addGroup(jPanelPerfilLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButtonFechar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanelPerfilLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButtonExcluirPerfil)
                        .addComponent(jButtonAlterarPerfil)))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelPerfil, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelPerfil, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFecharActionPerformed
        dispose();
    }//GEN-LAST:event_jButtonFecharActionPerformed

    private void jButtonExcluirPerfilActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExcluirPerfilActionPerformed
            if (perfil.getUsuarios().isEmpty()) {
            int option = JOptionPane.showConfirmDialog(this, "Tem certeza que deseja excluir o perfil " + perfil + "?", "Alerta", JOptionPane.WARNING_MESSAGE);
            if (option == JOptionPane.YES_OPTION) {
                new Dao(Perfil.class).remove(perfil.getId());
                    JOptionPane.showMessageDialog(this, "Perfil " + perfil + " excluído com sucesso!", "Sucesso", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            }
        } else {
            JOptionPane.showMessageDialog(this, "Há usuários vinculados a esse perfil!", "Alerta", JOptionPane.WARNING_MESSAGE);
            String option;
            do {
                option = JOptionPane.showInputDialog(this, "1 - Para excluir todos os usuários vinculados a esse perfil;\n"
                        + "2 - Para redefinir um perfil existente para os usuários vinculados a esse perfil;",
                        "Informe a opção",
                        JOptionPane.QUESTION_MESSAGE);
            } while (!option.equals("1") && !option.equals("2"));

            if (option.equals("1")) {
                boolean excluir = true;
                for (Usuario usuario : perfil.getUsuarios()) {
                    if (usuario.hasDebitosPendentes() || usuario.hasEmprestimos()) {
                        excluir = false;
                    }
                }
                if (excluir) {
                    for (Usuario usuario : perfil.getUsuarios()) {
                        new DaoUsuario().remove(usuario.getId());
                    }
                    new Dao(Perfil.class).remove(perfil.getId());
                    JOptionPane.showMessageDialog(this, "Perfil " + perfil + " excluído com sucesso!", "Sucess", JOptionPane.INFORMATION_MESSAGE);
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(this, "Há usuários vinculados há esse perfil\n"
                            + " que possuem empréstimos ativos ou débitos pendentes!", "Erro", JOptionPane.ERROR_MESSAGE);
                }
            } else {                
                String opcoes = "";
                List<Perfil> list = new Dao<Perfil>(Perfil.class).list();
                for (int i = 0; i < list.size(); i++) {
                    if (!perfil.equals(list.get(i))) {
                        opcoes = i + 1 + " - " + list.get(i).getNome() + "\n";
                    }
                }

                option = JOptionPane.showInputDialog(this, opcoes,
                        "Informe a opção",
                        JOptionPane.QUESTION_MESSAGE);
                int op = Integer.parseInt(option);
                if (op > 0 && op <= list.size()) {
                    Perfil novoPerfil = list.get(op - 1);
                    DaoUsuario daoUsuario = new DaoUsuario();
                    for (Usuario u : perfil.getUsuarios()) {
                        u.setPerfil(novoPerfil);
                        daoUsuario.update(u);
                    }
                    perfil.setUsuarios(null);
                    new Dao<Perfil>(Perfil.class).remove(perfil.getId());
                    JOptionPane.showMessageDialog(this, "Perfil " + perfil + " excluído com sucesso!", "Sucess", JOptionPane.INFORMATION_MESSAGE);
                    dispose();
                }                

            }
        }
    }//GEN-LAST:event_jButtonExcluirPerfilActionPerformed

    private void jButtonAlterarPerfilActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAlterarPerfilActionPerformed
        setVisible(false);
        new JDialogCadastrarAlterarPerfil((JFrame) getParent(), true, perfil).setVisible(true);
        dispose();
    }//GEN-LAST:event_jButtonAlterarPerfilActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAlterarPerfil;
    private javax.swing.JButton jButtonExcluirPerfil;
    private javax.swing.JButton jButtonFechar;
    private javax.swing.JLabel jLabelAtividades;
    private javax.swing.JLabel jLabelNome;
    private javax.swing.JLabel jLabelNumeroMaximo;
    private javax.swing.JLabel jLabelTempoMaximo;
    private javax.swing.JList jListAtividadesAdicionadas;
    private javax.swing.JPanel jPanelPerfil;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextFieldNome;
    private javax.swing.JTextField jTextFieldNumeroMaximo;
    private javax.swing.JTextField jTextFieldTempoMaximo;
    // End of variables declaration//GEN-END:variables

    private void preencherCampos() {
        jTextFieldNome.setText(perfil.getNome());
        jTextFieldNumeroMaximo.setText(String.valueOf(perfil.getMaxEmprestimos()));
        jTextFieldTempoMaximo.setText(String.valueOf(perfil.getTempoEmprestimo()));
        DefaultListModel model = new DefaultListModel();
        for (Atividade atividade : perfil.getAtividades()) {
            model.addElement(atividade);
        }
        jListAtividadesAdicionadas.setModel(model);
    }
}
